package com.web;


import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.entity.Employee;
import com.service.EmployeeService;

public class UploadHead extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Employee employee=(Employee)request.getSession().getAttribute("employee");
		
		String path=getServletContext().getRealPath("/img");
		
		File file=new File(path+"/");
		File temp=new File("c:/temp");

		if(!file.exists()){
			file.mkdir();
		}
		
		if(!temp.exists()){
			temp.mkdir();
		}
		
		
		if(ServletFileUpload.isMultipartContent(request)){
			DiskFileItemFactory factory=new DiskFileItemFactory();
			factory.setSizeThreshold(1024*10);
			factory.setRepository(temp);
			
			ServletFileUpload upload=new ServletFileUpload(factory);
			upload.setFileSizeMax(1024*1024*10);
			
			try {
				List<FileItem> items= upload.parseRequest(request);
				
				for(FileItem item:items){
					if(!item.isFormField()){
						
						String str=item.getName().substring(item.getName().indexOf("."));
						
						UUID uuid=UUID.randomUUID();
						String filename=uuid.toString()+str;
						
						File f=new File(file,filename);
						item.write(f);
						
						employee.setPic("img/"+filename);
						EmployeeService employeeService=new EmployeeService();
						employeeService.update(employee);
					}
					
				}
				
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		response.sendRedirect("projectlist.jspx");
	}

}
